package com.shishi.tech.paipai.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.support.multidex.MultiDex;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.shishi.tech.paipai.service.LogCollectorService;

import java.util.ArrayList;
import java.util.List;

import http.ApiUtil;
import utils.SharedPreUtil;


/**
 * 类名称：BaseApplication
 * 类描述:
 * 创建人：Administrator
 * 创建时间：2015年7月2日 下午4:57:51
 * 修改人：Administrator
 * 修改时间：2015年7月2日 下午4:57:51
 * 修改备注:
 *
 * @see
 */
public class BaseApplication extends Application {
    /** 存放每个堆栈里的 Activity .*/
    private static List<Activity> activityList = new ArrayList<Activity>();
    private static BaseApplication mIns = null;

    /***********************应用基本参数信息*****************************/


    /** 应用版本号 .*/
    public String versionName;



    @Override
    public void onCreate() {
        super.onCreate();
        mIns = this;
        initAsynicTaskClass();
        initImageLoaderConfig();
        initPackageInfo();
//        initOtherVars();
        //输出控制台日志信息的服务,日志路径：mdlk_personal/log
        if (ApiUtil.isDebug()) {
            Intent intent = new Intent(this, LogCollectorService.class);
            startService(intent);
        }
//        initHotfix();
    }


    public static BaseApplication getInstance() {
        return mIns;
    }

    /**
     * Getting NoClassDefFoundError: android.os.AsyncTask
     */
    public void initAsynicTaskClass() {
        try {
            Class.forName("android.os.AsyncTask");
        } catch (Throwable ignore) {
        }
    }

    /**
     * ImageLoader 初始化 设置
     */
    public void initImageLoaderConfig() {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480, 480)
                .threadPoolSize(3)// default  线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
                .diskCacheFileCount(1000)  // 可以缓存的文件数量
                .diskCacheSize(100 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
                .imageDownloader(new BaseImageDownloader(getApplicationContext(), 5 * 1000, 30 * 1000))//connectTimeout(5s),readTimeout(30s)超时时间
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())// default为使用HASHCODE对UIL进行加密命名， 还可以用MD5(new Md5FileNameGenerator())加密
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                        //.writeDebugLogs() // 打印debug log
                .build(); //开始构建
        ImageLoader.getInstance().init(config);
    }

    /**
     * 数据库 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * @return
     */
/*    public static DaoMaster daoMaster;

    public static DaoSession daoSession;

    public static SQLiteDatabase db;

    public static String DB_NAME;

    public static DaoMaster getDaoMaster(Context context) {
        String userId = SharedPreUtil.getInstance().getValue(SharedPreUtil.USER_ID);
        if (daoMaster == null) {
            DB_NAME = "persion.mar.db";
            DB_NAME = userId + DB_NAME;
            if (null == context) {
                context = getInstance();
            }
            OpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());

        }
        return daoMaster;
    }

    public static DaoMaster getDaoMaster(SQLiteDatabase db) {
        if (daoMaster == null) {
            daoMaster = new DaoMaster(db);
            *//**删除本地超过时间的历史数据*//*
            DelDatadb.delNewChatDataEntity(daoMaster.getDatabase());
        }
        return daoMaster;
    }

    public static DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            daoMaster = getDaoMaster(context);
            if (ApiUtil.isDebug()) {
                QueryBuilder.LOG_SQL = true;
                QueryBuilder.LOG_VALUES = true;
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    public static SQLiteDatabase getsqlLiteDatabase(Context context) {
        if (db == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context);
            }
            db = daoMaster.getDatabase();
        }
        return db;
    }*/

    public static List<Activity> getActivityList() {
        return activityList;
    }

    /**
     * 清空指向数据库指针（用户切换建立新库）
     */
    public static void clearDBIndication() {
       /* DBHelper.helper = null;
        BaseApplication.daoSession = null;
        BaseApplication.daoMaster = null;
        FriendCircleDBHelper.helper = null;
        MicroCircleDBHelper.helper = null;
        DatingCircleDBHelper.helper = null;
        WorkCircleDBHelper.helper = null;
        JobCircleDBHelper.helper = null;
        SharedPreUtil.sharePreUtil = null;
        SensitiveDbUtil.sensitiveDbUtil = null;
        WarnDbUtil.warnDbUtil = null;
        ServerSensitiveUtil.serverSensitivecUtil = null;
        ServerWarnUtil.serverWarnUtil = null;
        BusCircleDBHelper.helper = null;
        HitMoneyDBUtil.hitMoneyDBUtil = null;
        ChatAdapterUtil.chatAdapterUtil = null;
        MessageUtil.messageUtil = null;
        EmotionsDbHelper.emotionsDbHelper = null;
        ChatMsgFty.chatMsgFty = null;
        IMDBHelper.helper = null;
        RecordDBHelper.helper = null;*/
    }

    /*** 清空所以的Activity 必须是登录上应用，如果没有登录可能没有*/
    public void close(boolean isLogin) {
       /* anVoices.clear();//清空所有播报记录
        if (isLogin){
            Activity activity = getRunningActivity();
            Activity context = activity == null ? (activityList.size() > 0 ? activityList.get(0) : null) : activity;
            if (context != null){
                //退出登录界面
                ActivityUtil.next(context,LoginAccountActivity.class);
                //关闭IM连接服务
                LongCycleService.stopService(context);
                //关闭自动播报服务
                AutoVoiceService.stopService(context);
            }
            //退出账号，制空id和 token
            SharedPreUtil.getInstance().putValue(SharedPreUtil.USER_ID, "");
            SharedPreUtil.getInstance().putValue(SharedPreUtil.USER_TOKEN, "");
            clearDBIndication();//清空单利引用
            PushClient.exitAccount();//关闭IM,初始化配置参数
        }
        for (Activity activity : activityList) {
            if (isLogin){
                if (!activity.getClass().getName().equals(LoginAccountActivity.class.getName())){
                    activity.finish();
                }
            }else {
                activity.finish();
            }
        }*/

    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    /**
     * 获取包名信息
     */
    public PackageInfo initPackageInfo() {
        PackageInfo pi = null;
        try {
            PackageManager pm = this.getPackageManager();
            pi = pm.getPackageInfo(this.getPackageName(), 0);
            SharedPreUtil.getInstance(this).putValue(SharedPreUtil.VERSION_NAME, pi.versionName);
            SharedPreUtil.getInstance(this).putValue(SharedPreUtil.VERSION_CODE, pi.versionCode);
            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }



    /**
     * 获取mac地址
     * @return
     */
    public String getLocalMacAddress() {
        WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**
     * 获取当前运行的Activity
     */
    public String getRunningActivityName() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        return runningActivity;
    }

    /**
     * 获取当前运行的Activity
     */
    public Activity getRunningActivity() {
        for (Activity activity : activityList) {
            if (activity.getClass().getName().equals(getRunningActivityName())){
                return activity;
            }
        }
        return null;
    }

    /**
     * 获取当前Activity 是否已经存在栈中
     */
    public boolean existStackActivityName(String activtyname) {
        List<Activity> activities = BaseApplication.getInstance().getActivityList();
        for (int i = 0; i < activities.size(); i++) {
            String temp = activities.get(i).getClass().getName();
            if (activtyname.equals(temp)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 保持 dialog 唯一弹框
     */
    public static Dialog dialog;


    /** 设置屏幕保存高亮 */
    private PowerManager.WakeLock wakeLock = null;

    /** 设置屏幕保存高亮不熄屏 */
   /* public void setPowerManager() {
        if (SharedPreUtil.getInstance().announceOnOff() && IMDBHelper.getInstance().announces().size() > 0) {
            if (wakeLock == null) {
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, this.getClass().getCanonicalName());
                if (wakeLock != null)
                    wakeLock.acquire();
            }
        } else {
            if (wakeLock != null){
                wakeLock.release();
            }
            wakeLock = null;
        }
    }*/

    /**阿里百川 hotfix 热补丁技术*/
    private void initHotfix() {
       /* String appId = "73991-1";
        //初始化
        HotFixManager hotFixManager = HotFixManager.getInstance().initialize(this, getInstance().versionName, appId, mNewPatchListener);
        //查询最新patch
        hotFixManager.queryNewHotPatch();*/
    }

    /*NewPatchListener mNewPatchListener = new NewPatchListener() {
        @Override
        public void handlePatch(int patchVersion) {
            // TODO do something
            ToastUtil.showInfoMsg("请重启应用进行更新");
        }
    };*/

}
